function varargout = DrawMesh(varargin)
% This file is part of CISNE.
%
%     CISNE is free software: you can redistribute it and/or modify
%     it under the terms of the GNU General Public License as published by
%     the Free Software Foundation, either version 3 of the License, or
%     any later version.
%
%     CISNE is distributed in the hope that it will be useful,
%     but WITHOUT ANY WARRANTY; without even the implied warranty of
%     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%     GNU General Public License for more details.
%
%     You should have received a copy of the GNU General Public License
%     along with CISNE.  If not, see <http://www.gnu.org/licenses/>.

% Copyright 2011. Jose Maria Garcia-Valdecasas Bernal

% Edit the above text to modify the response to help DrawMesh

% Last Modified by GUIDE v2.5 29-Jun-2011 02:00:04

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @DrawMesh_OpeningFcn, ...
                   'gui_OutputFcn',  @DrawMesh_OutputFcn, ...
                   'gui_LayoutFcn',  [], ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
   gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before DrawMesh is made visible.
function DrawMesh_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   unrecognized PropertyName/PropertyValue pairs from the
%            command line (see VARARGIN)

% Choose default command line output for DrawMesh
handles.output = hObject;

axes(handles.axes1); %#ok<MAXES>
axis image;
axis off;
axes(handles.cbar); %#ok<MAXES>
axis off;

warning('off','MATLAB:colorbar:DeprecatedV6Argument');
% Update handles structure
guidata(hObject, handles);

% UIWAIT makes DrawMesh wait for user response (see UIRESUME)
uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = DrawMesh_OutputFcn(hObject, eventdata, handles)
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --- Executes on selection change in popupmenu2.
function popupmenu2_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu2 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu2


% --- Executes during object creation, after setting all properties.
function popupmenu2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%cargamos el directorio donde estel proyecto completo (SWN y OUT)
projectdir=uigetdir('','Select folder with project data');
set(handles.edit1,'String',projectdir);

listaAux=dir(fullfile(projectdir,'OUT','*.tbl')); 
m_listaTablas={listaAux.name};
listaAux=dir(fullfile(projectdir,'SWN','*.swn')); 
m_listaCasos={listaAux.name};
m_list=m_listaCasos;
%obtencion de los casos de manera "simple".
for j=1:length(m_listaCasos)
    aux=regexp(m_listaCasos{j},'-H','split');
    aux=regexp(aux{2},'T','split');
    H=regexprep(aux{1},'_','\.');
    aux=regexp(aux{2},'D','split');
    T=regexprep(aux{1},'_','\.');
    aux=regexp(aux{2},'Lvl','split');
    D=str2double(regexprep(aux{1},'_','\.'));
    num=str2double(m_listaCasos{j}(1:2));
    if(num>1)
        kind='nested';
    else
        kind='';
    end
    m_list{j}=sprintf('H: %s | T: %s | D: %s | %s',H,T,dir2txt(D),kind);
end

set(handles.popupmenu1,'String',m_list);
handles.m_Cases=m_listaCasos;
handles.m_Tables=m_listaTablas;

% Update handles structure
guidata(hObject, handles);

%update display with current case
updateDisplay(handles);


% --- Executes on selection change in popupmenu1.
function popupmenu1_Callback(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popupmenu1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popupmenu1
updateDisplay(handles);

% --- Executes during object creation, after setting all properties.
function popupmenu1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popupmenu1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

function updateDisplay(handles)
if(~isempty(get(handles.popupmenu1,'String')))
    
val=get(handles.popupmenu1,'Value');
project=get(handles.edit1,'String');
swnfile=fullfile(project,'SWN',handles.m_Cases{val});
tblfile=fullfile(project,'OUT',handles.m_Tables{val});


%display wave data

aux=regexp(handles.m_Cases{val},'-H','split');
aux=regexp(aux{2},'T','split');
set(handles.text4,'String',sprintf('H: %s',regexprep(aux{1},'_','\.')));
aux=regexp(aux{2},'D','split');
set(handles.text5,'String',sprintf('T: %s',regexprep(aux{1},'_','\.')));
aux=regexp(aux{2},'Lvl','split');
set(handles.text6,'String',sprintf('Dir: %s',regexprep(aux{1},'_','\.')));


%Plot image

if ~isempty(regexp(swnfile,'-nst', 'once'))
    %se trata de una malla anidada!!
    [path,fname,ext]=fileparts(swnfile);
    partes=regexp(fname,'-nst','split');
    fname=[partes{1} partes{2} ext];
    fname(2)='1';
    swnfile=fullfile(path,fname);
    nsttxt='_nested';
else
    nsttxt='';
end
fh=fopen(swnfile,'r');
seguir=true; %variable de control
while (~feof(fh)&&seguir)
    line=fgetl(fh);
    elem=regexp(line,'\s+', 'split');
    
    %condiciones contorno
    if ~isempty(findstr(elem{1},'BOUN'))&&~isempty(findstr(elem{2},'SIDE'))
        
        caso_Hs=sscanf(elem{6},'%f');
        caso_Tp=sscanf(elem{7},'%f');
        caso_Dir=sscanf(elem{8},'%f');
        seguir=false; %solo leemos las condiciones de oleaje 1 vez!!
        
    end
    
end

fclose(fh);

%cargamos el archivo en un objeto SWANTbl... alehop!
tabla=SWANTbl(tblfile);

%oleaje:
[Hsmap,X,Y]=tabla.genMesh('Hsig');
meshDir=tabla.genMesh('Dir');


[iLand,jLand]=find(Hsmap<0); %si la Hs es menor de 0... es tierra


for k=1:length(iLand)
    Hsmap(iLand(k),jLand(k)) = nan;
end

maxH=max(Hsmap(:));

axes(handles.axes1);
cla;
cla(handles.cbar,'reset');
imagesc(X,Y,Hsmap,[0 maxH]); 
set(gca,'YDir','normal');

if exist('private\MapaOla.dat','file')
    mapaola=dlmread('private\MapaOla.dat');
else
    mapaola=jet(256);
end
colormap(mapaola);
colorbar(handles.cbar,'peer',handles.axes1);
axis image
axis off
set(handles.axes1,'YDir','normal');

%y le sobreimprimos la direccion del oleaje... :)
hold on

UDir=-sind(meshDir).*(Hsmap./maxH);
VDir=cosd(meshDir).*(Hsmap./maxH);

for k=1:length(iLand)
    UDir(iLand(k),jLand(k)) = 0;
    VDir(iLand(k),jLand(k)) = 0;
end

%mostrar vectores cada 6 puntos por ejemplo
N=4;


[XX,YY]=meshgrid(X,Y);

quiver(XX(1:N:end,1:N:end),YY(1:N:end,1:N:end),UDir(1:N:end,1:N:end),...
    -VDir(1:N:end,1:N:end),0.7,'color','k');


costa=get(handles.edit2,'String');

if ~isempty(costa)
    cst=loadCst(costa);
    plotCst(handles.axes1,cst,[0.3 0.3 0.3]);
end

end


function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[fname,fpath]=uigetfile('*.cst','Selecciona el archivo .cst');
costa=fullfile(fpath,fname);
set(handles.edit2,'String',costa);
updateDisplay(handles);
